//
//  YCCommonUtil.m
//  YCBaseModule
//
//  Created by Apple on 2022/11/8.
//

#import "YCCommonUtil.h"

@implementation YCCommonUtil

+ (NSString *)getRandomStringWithLength:(NSInteger)len {
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (NSInteger i = 0; i < len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex:arc4random_uniform((int)[letters length])]];
    }
    return randomString;
}

+ (NSString *)changeIntToString:(NSInteger)agent {
    return [NSString stringWithFormat:@"%ld", agent];
}

+ (NSString *)getRequestTimestamp {
    return [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970] * 1000];
}

+ (NSDictionary *)dictionaryWithJSON:(id)json {
    if (!json || json == (id)kCFNull) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return dic;
}

+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

+ (NSString *)getWeekDayStrWithDays:(NSString *)weekdays {
    NSString *weekDayStr = @"";
    if (weekdays.length == 0) {
        return @"请选择服务时间";
    }
    NSInteger days = 0;
    NSInteger workdays = 0;
    if ([weekdays containsString:@"1"]) {
        weekDayStr = @"周一";
        days++;
        workdays++;
    }
    if ([weekdays containsString:@"2"]) {
        if ([weekDayStr isEqualToString:@""]) {
            weekDayStr = @"周二";
        }
        else {
            weekDayStr = [NSString stringWithFormat:@"%@、周二",weekDayStr];
        }
        days++;
        workdays++;
    }
    if ([weekdays containsString:@"3"]) {
        if ([weekDayStr isEqualToString:@""]) {
            weekDayStr = @"周三";
        }
        else {
            weekDayStr = [NSString stringWithFormat:@"%@、周三",weekDayStr];
        }
        days++;
        workdays++;
    }
    if ([weekdays containsString:@"4"]) {
        if ([weekDayStr isEqualToString:@""]) {
            weekDayStr = @"周四";
        }
        else {
            weekDayStr = [NSString stringWithFormat:@"%@、周四",weekDayStr];
        }
        days++;
        workdays++;
    }
    if ([weekdays containsString:@"5"]) {
        if ([weekDayStr isEqualToString:@""]) {
            weekDayStr = @"周五";
        }
        else {
            weekDayStr = [NSString stringWithFormat:@"%@、周五",weekDayStr];
        }
        days++;
        workdays++;
    }
    if ([weekdays containsString:@"6"]) {
        if ([weekDayStr isEqualToString:@""]) {
            weekDayStr = @"周六";
        }
        else {
            weekDayStr = [NSString stringWithFormat:@"%@、周六",weekDayStr];
        }
        days++;
        workdays=0;
    }
    if ([weekdays containsString:@"0"]) {
        if ([weekDayStr isEqualToString:@""]) {
            weekDayStr = @"周日";
        }
        else {
            weekDayStr = [NSString stringWithFormat:@"%@、周日",weekDayStr];
        }
        days++;
        workdays=0;
    }
    if (days==7) {
        return @"每天";
    }
    if (workdays==5) {
        return @"工作日";
    }
    return weekDayStr;
}

+ (NSString *)getRateAndUnitStringByRateNumber:(NSNumber *)rate isBit:(BOOL)isBit
{
    double rateValue = [rate doubleValue];
    double TBValue = 1024 * 1024 *1024.f;
    double PBValue = 1024 * 1024 *1024 * 1024.f;
    NSString *rateNumberString = nil;
    NSString *unit = @"B";
    if(isBit)
    {
        unit = @"b";
    }
    
    if(rateValue < 1024.f)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.0fK%@",rateValue,unit];
    }
    else if(rateValue >= 1024.f && rateValue < 1024*1024.f)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fM%@",rateValue/1024.f,unit];
    }
    else if(rateValue >= 1024*1024.f && rateValue < TBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fG%@",rateValue/(1024*1024.f),unit];
    }
    else if(rateValue >= TBValue && rateValue < PBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fT%@",rateValue/TBValue,unit];
    }
    else if(rateValue >= PBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fP%@",rateValue/PBValue,unit];
    }
    else{
        rateNumberString =
        [NSString stringWithFormat:@"%.0fK%@",rateValue,unit];
    }
    
    return rateNumberString;
}

+ (NSString *)getRateStringByRateNumber:(NSNumber *)rate
{
    double rateValue = [rate doubleValue];
    double TBValue = 1024 * 1024 *1024.f;
    double PBValue = 1024 * 1024 *1024 * 1024.f;
    NSString *rateNumberString = nil;
    if(rateValue < 1024.f)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.0f",rateValue];
    }
    else if(rateValue >= 1024.f && rateValue < 1024*1024.f)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1f",rateValue/1024.f];
    }
    else if(rateValue >= 1024*1024.f && rateValue < TBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1f",rateValue/(1024*1024.f)];
    }
    else if(rateValue >= TBValue && rateValue < PBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1f",rateValue/TBValue];
    }
    else if(rateValue >= PBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1f",rateValue/PBValue];
    }
    else{
        rateNumberString =
        [NSString stringWithFormat:@"%.0f",rateValue];
    }
    
    return rateNumberString;
}

+ (NSString *)getRateUnitStringByRateNumber:(NSNumber *)rate isBit:(BOOL)isBit
{
    double rateValue = [rate doubleValue];
    double TBValue = 1024 * 1024 *1024.f;
    double PBValue = 1024 * 1024 *1024 * 1024.f;
    NSString *rateNumberString = nil;
    NSString *unit = @"B";
    if(isBit)
    {
        unit = @"b";
    }
    if(rateValue < 1024.f)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.0fK%@",rateValue,unit];
    }
    else if(rateValue >= 1024.f && rateValue < 1024*1024.f)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fM%@",rateValue/1024.f,unit];
    }
    else if(rateValue >= 1024*1024.f && rateValue < TBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fG%@",rateValue/(1024*1024.f),unit];
    }
    else if(rateValue >= TBValue && rateValue < PBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fT%@",rateValue/TBValue,unit];
    }
    else if(rateValue >= PBValue)
    {
        rateNumberString =
        [NSString stringWithFormat:@"%.1fP%@",rateValue/PBValue,unit];
    }
    else{
        rateNumberString =
        [NSString stringWithFormat:@"%.0fK%@",rateValue,unit];
    }
    
    return [rateNumberString substringWithRange:NSMakeRange(rateNumberString.length-2, 2)];
}

+ (void)printJsonData:(NSData *)jsonData
{
    NSLog(@"json Str: %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
}

+ (NSString *)getImageDataBase64:(UIImage *)image
{
    NSData *imageData =nil;
    
    //图片要压缩的比例，此处100根据需求，自行设置
    CGFloat x =100 / image.size.height;
    if (x >1)
    {
        x = 1.0;
    }
    
    imageData = UIImageJPEGRepresentation(image, x);
    
    return [@"data:image/png;base64," stringByAppendingString:[imageData base64EncodedStringWithOptions:0]];
}

#pragma mark - 银行卡账号形式转换
// 正常号转银行卡号 － 增加4位间的空格
+ (NSString *)normalNumToBankNum:(NSString *)normalNum
{
    if (normalNum == nil || normalNum.length == 0) {
        return @"";
    }
    
    NSString *tmpStr = [YCCommonUtil bankNumToNormalNum:normalNum];
    
    NSInteger size = (tmpStr.length / 4);
    
    NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];
    for (int n = 0;n < size; n++)
    {
        [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(n*4, 4)]];
    }
    
    [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(size*4, (tmpStr.length % 4))]];
    
    tmpStr = [tmpStrArr componentsJoinedByString:@" "];
    //去掉前后的空格
    if ([tmpStr hasPrefix:@" "] || [tmpStr hasSuffix:@" "] == YES)
    {
        tmpStr = [tmpStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    
    return tmpStr;
}

// 银行卡号转正常号 － 去除4位间的空格
+ (NSString *)bankNumToNormalNum:(NSString *)bankNum
{
    return [bankNum stringByReplacingOccurrencesOfString:@" " withString:@""];
}

+ (NSString *)bankNumToSecret:(NSString *)bankNum
{
    if (bankNum.length < 8 || bankNum == nil)
    {
        return bankNum;
    }
    NSString *star = @"";
    for (int i = 0; i < (bankNum.length-8) ; i++)
    {
        star = [star stringByAppendingString:@"*"];
    }
    
    NSString *tmpStr = [bankNum stringByReplacingCharactersInRange:NSMakeRange(4, bankNum.length-8) withString:star];
    return tmpStr;
}

#pragma mark - 通过 parentId 筛选 城市或区（县）
+ (NSArray *)filterAraeFromAreaArray:(NSArray *)areaArray useParentId:(NSInteger)parentId
{
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"parentId == %@", @(parentId)];
    NSArray *resultArray = [areaArray filteredArrayUsingPredicate:pred];
    return resultArray;
}

#pragma mark - 通过 parentNo 筛选 分类
+ (NSArray *)filterClassFromAreaArray:(NSArray *)areaArray useParentNo:(NSString *)parentNo
{
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"parentNo == %@",parentNo];
    NSArray *resultArray = [areaArray filteredArrayUsingPredicate:pred];
    return resultArray;
}

#pragma mark - 限制只能输入数字输入
+ (BOOL)validateNumber:(NSString*)number
{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

//压缩图片
+ (UIImage *)compressImageWith:(UIImage *)image
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 640;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return newImage;
    
}


//去除emoji表情的方法
+ (NSString*)disable_EmojiString:(NSString *)text
{
    //去除表情规则
    //  \u0020-\\u007E  标点符号，大小写字母，数字
    //  \u00A0-\\u00BE  特殊标点  (¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾)
    //  \u2E80-\\uA4CF  繁简中文,日文，韩文 彝族文字
    //  \uF900-\\uFAFF  部分汉字
    //  \uFE30-\\uFE4F  特殊标点(︴︵︶︷︸︹)
    //  \uFF00-\\uFFEF  日文  (ｵｶｷｸｹｺｻ)
    //  \u2000-\\u201f  特殊字符(‐‑‒–—―‖‗‘’‚‛“”„‟)
    // 注：对照表 http://blog.csdn.net/hherima/article/details/9045765
    
    NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u2000-\\u201f\r\n]"
                                                                                options:NSRegularExpressionCaseInsensitive
                                                                                  error:nil];
    
    
    NSString* result = [expression stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@""];
    
    return result;
}

//去除非中文的方法
+ (NSString*)disable_Non_CineseString:(NSString *)text
{
    NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:@"[^\u4e00-\u9fa5]"
                                                                                options:NSRegularExpressionCaseInsensitive
                                                                                  error:nil];
    
    
    NSString* result = [expression stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@""];
    
    return result;
}

#pragma mark - 判断沙盒文件是否存在
+ (BOOL)fileExistingWithFileName:(NSString *)fileName {
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [path objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:plistPath];
}


#pragma 正则匹配用户密码6-18位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

#pragma 正则只能输入数字和字母
+ (BOOL)checkTeshuZifuNumber:(NSString *) CheJiaNumber{
    NSString *bankNum=@"^[A-Za-z0-9]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bankNum];
    BOOL isMatch = [pred evaluateWithObject:CheJiaNumber];
    return isMatch;
}

+ (NSString *) nullDefultString: (NSString *)fromString null:(NSString *)nullStr{
    if ([fromString isEqualToString:@""] || [fromString isEqualToString:@"(null)"] || [fromString isEqualToString:@"<null>"] || [fromString isEqualToString:@"null"] || fromString==nil) {
        return nullStr;
    }else{
        return fromString;
    }
}

// 判断字符串为空或只为空格
+(BOOL)isBlankString:(NSString *)string
{
    if (string == nil) {
        return YES;
    }
    if (string == NULL) {
        return YES;
    }
    if([string isKindOfClass:[NSString class]] == NO)
    {
        return YES;
    }
    if(string.length == 0)
    {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        return YES;
    }
    if ([string.lowercaseString isEqualToString:@"(null)"] || [string.lowercaseString isEqualToString:@"null"] || [string.lowercaseString isEqualToString:@"<null>"])
    {
        return YES;
    }
    return NO;
}

+ (NSString *)getMoneyStringWithMoneyNumber:(double)money {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    // 设置格式
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:money]];
    return formattedNumberString;
}


+ (NSString *)connectedTogetherWithString:(NSString *)string {
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return string;
}

void yc_runOnMainThread(void (^block)(void)) {
    if ([NSThread isMainThread]) {
        if (block) {
            block();
        }
    } else {
        if (block) {
            dispatch_async(dispatch_get_main_queue(), block);
        }
    }
}

+ (UIImage *)thumbWithImage:(UIImage *)sourceImage{
    //缩略为 宽为162  高为90
    //对图像尺寸进行压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    
    CGFloat scale = height/width;
    width = 162;
    height = width * scale;
    //进行尺寸重绘
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (UIImage *)zipScaleWithImage:(UIImage *)sourceImage{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width > 1280 || height > 1280) {
        if (width > height) {
            CGFloat scale = height/width;
            width = 1280;
            height = width * scale;
        }else{
            CGFloat scale = width/height;
            height = 1280;
            width = height * scale;
        }
        //2.宽大于1280高小于1280
    }else if(width > 1280|| height < 1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width * scale;
        //3.宽小于1280高大于1280
    }else if(width < 1280|| height > 1280){
        CGFloat scale = width/height;
        height = 1280;
        width = height * scale;
        //4.宽高都小于1280
    }
    //进行尺寸重绘
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //进行图像的画面质量压缩
    NSData *data = UIImageJPEGRepresentation(newImage, 0.5);
    if (data.length/1024.f > 512) { //大于1MB
        if (data.length/1024.f > 1024) {//1M以及以上
            data = UIImageJPEGRepresentation(newImage, 0.3);
        }else if (data.length/1024.f > 512) {//0.5M-1M
            data = UIImageJPEGRepresentation(newImage, 0.4);
        }
    }
    
    UIImage *zipImage = [UIImage imageWithData:data];
    return zipImage;
}

+ (BOOL)checkPlateNumber:(NSString *)number {
    NSString *str = @"^[\\u4e00-\\u9fa5][A-Z][A-Za-z0-9]{5,6}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
    BOOL isMatch = [pred evaluateWithObject:number];
    return isMatch;
}

+ (NSComparisonResult)compareFirstVersion:(NSString *)first secondVersion:(NSString *)second {
    if ([first isEqualToString:second]) {
        return NSOrderedSame;
    }
    
    NSArray *firstArray = [first componentsSeparatedByString:@"."];
    NSArray *secondArray = [second componentsSeparatedByString:@"."];
    
    for (int i = 0; i < firstArray.count && i < secondArray.count; i++) {
        NSInteger a = [[firstArray objectAtIndex:i] integerValue];
        NSInteger b = [[secondArray objectAtIndex:i] integerValue];
        
        if (a > b) {
            return NSOrderedDescending;
        } else if (a < b) {
            return NSOrderedAscending;
        }
    }
    
    return NSOrderedSame;
}

@end
